// 用户注册
import userDao from "../Dao/user.js";
import {generateRandomString, httpResult, sendEmail_post, validateEmail} from "../utils/utils.js";
import {createRoleToken} from "../middleware/JWTToken.js";
import {retrievePassword_1} from "../utils/templateUtils.js";
import captchaDao from "../Dao/captcha.js";
import {captchaTypes} from "../roleType/captchaTypes.js";
import captchaNewDao from "../Dao/captchaNew.js";

// 注册 http://127.0.0.1:52001/user/register
export const register = async (req, res) => {
  let {username, password, email, invitation_code, verify_code} = req.body;
  if (!password) {
    throw new Error('密码不能为空');
  }
  if (!invitation_code) {
    throw new Error('邀请码不能为空');
  }
  let validName = await checkUserName(username);
  if (!validName) {
    throw new Error('用户名已存在');
  }
  let validEmail = await checkEmail(email);
  if (!validEmail) {
    throw new Error('邮箱已存在');
  }
  // if(!verify_code) {
  //   throw new Error("验证码不能为空");
  // }
  // 验证邀请码
  let inviterID = await userDao.getInviterID(invitation_code);
  if (!inviterID) {
    throw new Error('邀请码无效');
  }
  // 验证验证码
  // let verifyCodeResult = await captchaNewDao.verify(email, captchaTypes.EMAIL_REGISTER, verify_code);
  // if(!verifyCodeResult) {
  //   throw new Error("验证码错误");
  // }
  // 验证通过，注册用户
  const myInvitationCode = await createInviteCode();
  let result = await userDao.addUser(username, password, email, myInvitationCode, inviterID);
  // todo 返回jwt token、refreshToken
  let tokenObj = await createRoleToken(result.id);
  console.log(result);
  res.json(httpResult.success({...result, ...tokenObj}));
};

// 用户登录
export const login = async (req, res) => {
  let {username, password, email} = req.body;
  if (!username && !email) {
    throw new Error('登录账户不能为空');
  }
  if (!password) {
    throw new Error('密码不能为空');
  }
  // 验证用户名或邮箱是否存在
  let result = await userDao.getUserByUsernameOrEmail(username, email);
  if (!result) {
    throw new Error('登录账户不存在');
  }
  // 验证密码是否正确
  let validPassword = (password === result.password);
  if (!validPassword) {
    throw new Error('密码错误');
  }
  // todo 返回jwt token、refreshToken
  let tokenObj = await createRoleToken(result.id);
  // console.log(result, {...result, ...tokenObj});
  res.json(httpResult.success({...result, ...tokenObj}));
};

// 验证用户密码
export const verifyPassword = async (req, res) => {
  let {id, password} = req.body;
  // console.log(id, password);
  if (!id || !password) {
    throw new Error('用户id或密码不能为空');
  }
  let result = await userDao.checkUserWithId(id, password);
  if (!result) {
    throw new Error('密码错误');
  }
  res.json(httpResult.success({result: true}));
};

// 获取用户信息
export const getUserInfo = async (req, res) => {
  let {id} = req.body;
  if (!id) {
    throw new Error('请输入查询用户');
  }
  let userInfo = await userDao.getUserById(id);
  if (!userInfo) {
    throw new Error('用户不存在');
  }
  res.json(httpResult.success(userInfo));
};

// 获取用户邮箱根据id
export const getUserEmail = async (req, res) => {
  let {id} = req.body;
  if (!id) {
    throw new Error('请输入查询用户');
  }
  let userInfo = await userDao.getUserEmailById(id);
  if (!userInfo) {
    throw new Error('用户不存在');
  }
  res.json(httpResult.success(userInfo));
};

// todo 更新用户信息
export const updateUserInfo = async (req, res) => {
  let {id, username, email} = req.body;
};

// 验证邮箱、用户名唯一
export const checkUserDataUnique = async (req, res) => {
  let {email, username} = req.body;
  console.log(email, username);
  if (!email && !username) {
    throw new Error('验证数据不能为空');
  }
  // 查询数据库，判断用户名或邮箱是否已存在
  if (username) {
    let result = await checkUserName(username);
    console.log(result);
    res.json(httpResult.success({result}));
    return;
  }
  if (email) {
    let result = await checkEmail(email);
    res.json(httpResult.success({result}));
  }
};

// 验证邀请码
export const checkInviterCode = (req, res) => {
  let {invitation_code} = req.body;
  console.log(invitation_code);
  if(!invitation_code) {
    throw new Error('邀请码不能为空');
  }
  let result = userDao.getInviterID(invitation_code);
  if(!result) {
    res.json(httpResult.success({result: false}));
    return;
  }
  res.json(httpResult.success({result: true}));
};


// 验证名称
const checkUserName = async (username) => {
  if (validateEmail(username)) {
    throw new Error('用户名格式错误');
  }
  let result = await userDao.hasUsername(username);
  return !result;

};

// 验证邮箱
const checkEmail = async (email) => {
  if (!validateEmail(email)) {
    throw new Error('邮箱格式错误');
  }
  let result = await userDao.hasEmail(email);
  return !result;
};

// 生成邀请码
const createInviteCode = async () => {
  let code = generateRandomString(6).toUpperCase();
  // 检查数据库是否存在
  let result = await userDao.getInviterID(code);
  // 如果有再生成一个
  if (result) {
    return await createInviteCode();
  }
  // 没有就返回
  return code;
};



